package com.example.caloriedaily

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase

class DBAccessor(ctx: Context){
    private val helper:DBHelper = DBHelper(ctx, "mydb", 1)
    private var db: SQLiteDatabase = helper.readableDatabase

    //实现单件模式
    companion object {
        lateinit var instance:DBAccessor
        private var init = false
        fun getInstance(c: Context):DBAccessor{
            if (!init){
                instance = DBAccessor(c)
                init = true
            }
            return instance
        }
    }

    //关闭数据库
    fun closeDB() {
        if (db.isOpen)
            db.close()
    }

    //判断是否为可写数据库
    private fun isWritableDB(): Boolean {
        if (!db.isOpen || db.isReadOnly) return false
        return true
    }

    //判断是否为可读数据库
    private fun isReadableDB(): Boolean {
        if (!db.isOpen) return false
        return true
    }

    //删除数据
    fun removeNote(i:Int): Int {
        if (!isWritableDB())
            db = helper.writableDatabase
        return db.delete("notes","nid = ?",arrayOf(i.toString()))
    }

    //增加数据
    fun insertNote(t:String, c:String){
        if (!isWritableDB())
            db = helper.writableDatabase
        val values = ContentValues()
        values.put("time", t)
        values.put("content", c)
        db.insert("notes", null, values)
    }

    //查询所有数据
    fun getNotes(ns: ArrayList<Note>){
        if(!isReadableDB())
            db = helper.readableDatabase
        val q = "select * from notes"
        val cur = db.rawQuery(q, null)
        val c = cur.count
        if (c > 0) {
            cur.moveToFirst()
            while (true){
                val i = cur.getInt(0)
                val t = cur.getString(1)
                val co = cur.getString(2)
                val n = Note(i, t, co)
                ns.add(n)
                if (!cur.moveToNext()) break
            }
        }
        cur.close()
    }
}
